package cn.online.qa.service;


import cn.online.qa.entity.Questions;
import cn.online.qa.repository.QuestionsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional(readOnly = false)
public class QuestionsService {
//    @Resource
//    QuestionsDao questionsDao;
    @Autowired
    QuestionsRepository questionsRepository;

    //分页查询

    public org.springframework.data.domain.Page<Questions> paging(int pageNo, int pageSize){
        Sort sort =Sort.by(Sort.Order.desc("id"));

        PageRequest p=PageRequest.of(pageNo,pageSize,sort);
        return  questionsRepository.findAll(new Specification<Questions>(){
            @Override
            public Predicate toPredicate(Root<Questions> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                criteriaQuery.where(predicateList.toArray(new Predicate[0]));
                return criteriaQuery.getRestriction();
            }

        },p);
    }

    //获得该问题
    public Questions getQuestions(long id){
        return questionsRepository.getOne(id);
    }
    //添加问题
    public int addQuestions(Questions questions){
         questionsRepository.save(questions);
        return 1;
    }

    public int addanswerCount(long id,int answerCount){
       questionsRepository.addanswerCount(id,answerCount);
        return 1;
    }


}
